<template>
  <div v-loading="loading" class="engineer_level" element-loading-text="加载中...">
    <div class="header">
      <div class="btn_group">
        <HPlainButton @click="addType">添加等级</HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeAll(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeAll(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <el-input
          v-model.trim="name"
          placeholder="等级名称"
          clearable
          @keyup.enter="getList"
          @clear="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>
    <div class="table">
      <el-table
        ref="tableDom"
        border
        stripe
        resizable
        :data="tableData"
        height="100%"
        @selection-change="handleChange"
      >
        <el-table-column type="selection" width="40" fixed />
        <el-table-column
          show-overflow-tooltip
          type="index"
          :index="indexMethod"
          label="序号"
          width="50"
          :align="'center'"
          fixed="left"
        />
        <el-table-column show-overflow-tooltip prop="name" label="等级名称" min-width="150" />
        <el-table-column prop="name" label="状态" width="70" fixed="right" :align="'center'">
          <template #default="scope">
            <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
            <HStatus v-else>启用</HStatus>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />
        <el-table-column fixed="right" label="操作" width="90">
          <template #default="scope">
            <h-space>
              <HLink @click="editType(scope.row.id)">编辑</HLink>
              <h-link type="error" @click="handleDelEngineerLevel(scope.row)">删除</h-link>
            </h-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <Pagination
        ref="pagination"
        :list_total="total"
        @size-change="getList"
        @current-change="getList(false)"
      />
    </div>

    <!-- 添加/编辑  等级弹窗 -->
    <h-dialog v-model="addDialog" :title="formTitle" :loading="formLoading">
      <el-form
        ref="formRef"
        label-position="top"
        inline-message
        class="modal_form_content"
        :rules="rules"
        :model="form"
      >
        <el-form-item label="等级名称" prop="name">
          <el-input v-model.trim="form.name" clearable placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="等级状态" class="same_line">
          <el-radio-group v-model="form.status">
            <el-radio :value="false" size="small">启用</el-radio>
            <el-radio :value="true" size="small">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <HButton is-modal type="primary" @click="saveData(formRef)">保存</HButton>
        <HButton is-modal @click="addDialog = false">取消</HButton>
      </template>
    </h-dialog>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '../../../../../../../components/Pagination/index.vue'
  import { ref, reactive } from 'vue'
  import type { FormInstance, TableInstance } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Delete, Warning, ArrowDown, CircleCheck } from '@element-plus/icons-vue'
  import {
    getNetworkLevelList,
    getNetworkLevelDelete,
    getNetworkLevelDisable,
    getNetworkLevelDetail,
    getNetworkfieldcLevelSave,
  } from '../../../../../../../api/network'
  import { EngineerLevel } from './types'

  const handleDelEngineerLevel = (engineerLevel: EngineerLevel) => {
    if (tableDom.value) {
      tableDom.value.clearSelection()
      tableDom.value.toggleRowSelection(engineerLevel, true)
      changeAll(3)
    }
  }

  //列表序号
  const indexMethod = (index: number) => {
    return (index + 1) * 1
  }
  const name = ref('') // 等级名称

  const tableData = ref([]) // 列表数据
  const tableDom = ref<TableInstance | null>(null) // 列表dom

  const pagination = ref() // 分页dom
  const total = ref() // 总数目

  const addDialog = ref(false)
  const loading = ref(false)

  const formTitle = ref('')
  const formLoading = ref(false)

  const form = reactive({
    id: null,
    name: '',
    status: false,
  })

  // 表单元素
  const formRef = ref<FormInstance>()

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入等级名称', trigger: 'blur' }],
  })

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 获取分页数据
  const getPageData = (val) => {
    if (val) pagination.value.setPage()
    return {
      limit: pagination.value.size,
      name: name.value,
      page: pagination.value.current,
    }
  }

  // 获取列表数据
  const getList = async (val = true) => {
    loading.value = true
    await getNetworkLevelList(getPageData(val)).then((res) => {
      tableData.value = res.data.data.rows
      total.value = parseInt(res.data.data.total)
    })
    loading.value = false
  }

  // 添加等级
  const addType = () => {
    formTitle.value = '添加等级'
    form.id = null
    form.name = ''
    form.status = false
    addDialog.value = true
  }

  // 编辑等级
  const editType = async (id) => {
    addDialog.value = true
    formTitle.value = '编辑等级'
    formLoading.value = true
    await getNetworkLevelDetail(id).then((res) => {
      form.id = res.data.data.row.id
      form.name = res.data.data.row.name
      form.status = res.data.data.row.status
    })
    formLoading.value = false
  }

  // 保存方法
  const saveMethod = (method, data, dialog, load) => {
    load.value = true
    method(data).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 5000,
          plain: true,
          showClose: true,
        })
        dialog.value = false
        load.value = false
        getList()
      } else {
        ElMessage({
          message: res.data.message,
          type: 'warning',
          duration: 5000,
          plain: true,
          showClose: true,
        })
        load.value = false
        return
      }
    })
  }

  // 保存等级
  const saveData = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        saveMethod(getNetworkfieldcLevelSave, form, addDialog, formLoading)
      }
    })
  }

  // 批量操作的方法
  const changeMethod = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的等级`,
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    ElMessageBox({
      type: type === '删除' ? 'error' : 'warning',
      title: '提示',
      message: `确定${type}选中的等级?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 5000,
            plain: true,
            showClose: true,
          })
        })
      } else {
        await method(arr).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 5000,
            plain: true,
            showClose: true,
          })
          if (dialog != '') {
            dialog.value = false
          }
        })
      }
      tableDom.value.clearSelection()
      getList()
    })
  }

  // 修改等级状态
  const changeAll = (n) => {
    if (n == 1) {
      changeMethod('启用', getNetworkLevelDisable, selecttion.value, false, '')
    }
    if (n == 2) {
      changeMethod('禁用', getNetworkLevelDisable, selecttion.value, true, '')
    }
    if (n == 3) {
      changeMethod('删除', getNetworkLevelDelete, selecttion.value, 3, '')
    }
    if (n == 33) {
      changeMethod('删除', getNetworkLevelDelete, [form.id], 3, addDialog)
    }
  }

  // 返回方法
  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import './EngineerLevel.scss';
</style>
